#include <stdlib.h>

#include "fsl_debug_console.h"
#include "fsl_common.h"
#include "fsl_gpio.h"
#include "fsl_gint.h"
#include "fsl_pint.h"
#include "fsl_inputmux.h"
#include "fsl_inputmux_connections.h"

#include "board.h"
#include "clock_config.h"
#include "pin_mux.h"

#include "hardware/tarm_io.h"
#include "tarm_exit.h"


void gint0_callback(void);
void pint_intr_callback(pint_pin_int_t pintr, uint32_t pmatch_status);


void LimitIO_Init(void)
{
	CLOCK_EnableClock(kCLOCK_Iocon);
	CLOCK_EnableClock(kCLOCK_Gpio1);
	gpio_pin_config_t LIMITGPIO_config = {
			.pinDirection = kGPIO_DigitalInput,
			.outputLogic = 0U
	};

	GPIO_PinInit(GPIO, X_LIM_P, X_LIM_PIN, &LIMITGPIO_config);
	GPIO_PinInit(GPIO, Y_LIM_P, Y_LIM_PIN, &LIMITGPIO_config);
}

void LimitExit_Init(void)
{
	//GINT
//	GINT_Init(GINT0);
//	GINT_SetCtrl(GINT0, kGINT_CombineOr, kGINT_TrigEdge, gint0_callback);
//    GINT_ConfigPins(GINT0, kGINT_Port1, ~(1U << X_LIM_PIN), (1U << X_LIM_PIN));
//    GINT_EnableCallback(GINT0);

	//PINT
	//1-Connect trigger sources to PINT
	INPUTMUX_Init(INPUTMUX);
	INPUTMUX_AttachSignal(INPUTMUX, kPINT_PinInt0, kINPUTMUX_GpioPort1Pin5ToPintsel);
	//2-Initialize PINT
	PINT_Init(PINT);
	//3-Setup Pin Interrupt 0 for rising edge
	PINT_PinInterruptConfig(PINT, kPINT_PinInt0, kPINT_PinIntEnableRiseEdge, pint_intr_callback);
	//4-Enable callbacks for PINT0 by Index
	PINT_EnableCallbackByIndex(PINT, kPINT_PinInt0);
}

void Limit_Enable(void)
{
	PINT_EnableCallbackByIndex(PINT, kPINT_PinInt0);
}

void Limit_Disable(void)
{
	PINT_DisableCallbackByIndex(PINT, kPINT_PinInt0);
}

void gint0_callback(void)
{
	LED_RED_TOGGLE();
}

void pint_intr_callback(pint_pin_int_t pintr, uint32_t pmatch_status)
{
	LED_BLUE_TOGGLE();
}

